package com.jiang.mybatis.config.mybatis;

import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * <p>
 *  mybatis-plus一些自定义的配置
 * </p>
 *
 * @author jiang
 * @since 2021-05-30
 */
@Configuration
public class MybatisConfig {

    /**
     * 使用mybatis-plus 重写了SqlSessionFactory, 故需要使用 MybatisSqlSessionFactoryBean 代替原来的 SqlSessionFactory
     *
     * @param dataSource 数据源
     * @throws Exception 构建异常
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.jiang.mybatis.entity");
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/*Mapper*.xml"));

        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setDefaultEnumTypeHandler(EnumValueTypeHandler.class);
        sqlSessionFactoryBean.setConfiguration(config);

        // 配置分页插件
        sqlSessionFactoryBean.setPlugins();
        // 配置事务管理器
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }
}
